package io.potato.ts.service;

import io.potato.core.AppException;
import io.potato.core.CrudService;
import io.potato.core.util.AssertUtils;
import io.potato.ts.domain.Contacts;
import io.potato.ts.domain.ContactsGroup;
import io.potato.ts.domain.ContactsLink;
import io.potato.ts.repository.ContactsGroupRepository;
import io.potato.ts.repository.ContactsLinkRepository;
import io.potato.ts.repository.ContactsRepository;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 通讯录--联系人表服务类
 * 
 * @author timl
 *
 * <p>2019-01-07 15:13:58</p>
 */
@Service
@Transactional
public class ContactsService extends CrudService<Contacts, Integer> {

	@Autowired
	ContactsRepository repository;

	@Autowired
	ContactsGroupRepository groupRepository;

	@Autowired
	private ContactsLinkRepository linkRepository;

	@Override
	protected JpaRepository<Contacts, Integer> getRepository() {
		return repository;
	}

	/**
	 * 查询个人通讯录群组下的联系人
	 * @param userId  用户ID
	 * @param groupId 群组ID
	 * @param mobileNo  过滤号码
	 * @return
	 */
	public List<Contacts> findList(Integer userId, Integer groupId, String mobileNo) {
		return findList(userId, Arrays.asList(groupId), mobileNo);
	}

	/**
	 * 查询个人通讯录群组下的联系人
	 * @param userId  用户ID
	 * @param groupIds 群组ID列表
	 * @param mobileNo  过滤号码
	 * @return
	 */
	public List<Contacts> findList(Integer userId, List<Integer> groupIds, String mobileNo) {
		if (groupIds == null || groupIds.isEmpty()) {
			return new ArrayList<>();
		}
		if (mobileNo == null) {
			mobileNo = "";
		}
		return repository.findByGroupId(userId, groupIds, mobileNo);
	}

	/**
	 * 查询个人通讯录所有联系人
	 * @param userId  用户ID
	 * @param mobileNo  过滤号码
	 * @return
	 */
	public List<Contacts> findList(Integer userId, String mobileNo) {
		if (mobileNo == null) {
			mobileNo = "";
		}
		return repository.findByUserId(userId, mobileNo);
	}

	/**
	 * 查询共享通讯录群组下的联系人
	 * @param organId  单位ID
	 * @param groupId  群组ID
	 * @param mobileNo  过滤号码
	 * @return
	 */
	public List<Contacts> findShareList(Integer organId, Integer groupId, String mobileNo) {
		return findShareList(organId, Arrays.asList(groupId), mobileNo);
	}

	/**
	 * 查询共享通讯录群组下的联系人
	 * @param organId  单位ID
	 * @param groupIds  群组ID
	 * @param mobileNo  过滤号码
	 * @return
	 */
	public List<Contacts> findShareList(Integer organId, List<Integer> groupIds, String mobileNo) {
		if (groupIds == null || groupIds.isEmpty()) {
			return new ArrayList<>();
		}

		if (mobileNo == null) {
			mobileNo = "";
		}
		return repository.findShareByGroupId(organId, groupIds, mobileNo);
	}

	/**
	 * 查询共享通讯录群组下的所有联系人
	 * @param organId  单位ID
	 * @param mobileNo  过滤号码
	 * @return
	 */
	public List<Contacts> findShareList(Integer organId, String mobileNo) {
		if (mobileNo == null) {
			mobileNo = "";
		}
		return repository.findShareByOrganId(organId, mobileNo);
	}

	/**
	 * 添加个人联系人
	 * @param contacts  联系人
	 * @param groupId 所属群组
	 */
	public void saveContacts(Contacts contacts, Integer groupId) {
        AssertUtils.isNotNull(contacts.getUserId());

        checkAndGetGroup(contacts.getUserId(), groupId);

        contacts.setType(1);

        if (contacts.getId() != null && contacts.getId() > 0) {
        	linkRepository.deleteByContactsId(groupId, Arrays.asList(contacts.getId()));
		}

		save(contacts);

        ContactsLink link = new ContactsLink();
        link.setGroupId(groupId);
        link.setContractsId(contacts.getId());
        link.setUserId(contacts.getUserId());
        linkRepository.save(link);
    }

    /**
     * 添加共享联系人
     * @param contacts  联系人
     * @param groupId  所属群组
     */
    public void saveShareContacts(Contacts contacts, Integer groupId) {
        AssertUtils.isNotNull(contacts.getOrganId());

        checkAndGetShareGroup(contacts.getOrganId(), groupId);

        contacts.setType(2);

		if (contacts.getId() != null && contacts.getId() > 0) {
			linkRepository.deleteByContactsId(groupId, Arrays.asList(contacts.getId()));
		}

        save(contacts);

        ContactsLink link = new ContactsLink();
        link.setGroupId(groupId);
        link.setContractsId(contacts.getId());
        link.setOrganId(contacts.getOrganId());
        linkRepository.save(link);
    }

	private ContactsGroup checkAndGetGroup(Integer userId, Integer groupId) {
		if (groupId.equals(0)) {
			ContactsGroup cg0 = new ContactsGroup();
			return cg0;
		}

		Optional<ContactsGroup> cg = groupRepository.findById(groupId);
		if (!cg.isPresent()) {
			throw new AppException("通讯录群组不存在");
		}

		ContactsGroup group = cg.get();
		if (!userId.equals(group.getUserId())) {
			throw new AppException("通讯录群组不属于此用户");
		}

		return group;
	}

    private ContactsGroup checkAndGetShareGroup(Integer organId, Integer groupId) {
        if (groupId.equals(-1)) {
            ContactsGroup cg0 = new ContactsGroup();
            return cg0;
        }

        Optional<ContactsGroup> cg = groupRepository.findById(groupId);
        if (!cg.isPresent()) {
            throw new AppException("通讯录群组不存在");
        }

        ContactsGroup group = cg.get();
        if (!organId.equals(group.getUserId())) {
            throw new AppException("通讯录群组不属于此单位");
        }

        return group;
    }
	
}
